//
// Created by (cie_tea)15694 on 2024/5/23.
//
#include "EventController.h"
#include <unistd.h>
#include <fcntl.h>
#include <sstream>

EventController::EventController()
{
    // 构造函数中的初始化代码
}

EventController::~EventController()
{
    // 析构函数中的清理代码，确保释放所有资源
    //    for (auto& pair : connection_buffers) {
    //        delete pair.second;
    //    }
}

Session* EventController::get_connection_state(int fd)
{
    std::cout<<"fd:"<<fd<<std::endl;
    for (const auto& pair : session_map)
    {
        std::cout << "Key: " << pair.first << " Value: " << pair.second << std::endl;
    }
    auto it = session_map.find(fd);
    if (it != session_map.end())
    {
        return it->second;
    }
    return nullptr;
}


Session* EventController::handleNewConnection(int fd)
{
    Session* pSession = new Session(fd);
    session_map[fd] = pSession;
    return pSession;


    //    for (const auto& pair : session_map) {
    //        std::cout << "Key: " << pair.first << " Value: " << pair.second << std::endl;
    //    }
    //    auto it = session_map.find(fd);
    //    if (it != session_map.end()) {
    //        return it->second;
    //    }
    //    return nullptr;
}

int EventController::handleCloseConnection(int fd)
{
    auto it = get_connection_state(fd);
    if (it)
    {
        delete it;
    }
    session_map.erase(fd); // 直接移除元素
    return 0;

    // 处理关闭连接的代码
    //    removeConnection(fd);
    //    close(fd);
    //    std::stringstream ss;
    //    ss << "Error on fd = " << fd;
    //    LOG_INFO(ss.str());
}

void EventController::handleRecvEvent(int fd)
{
    // 处理读取事件的代码
}

void EventController::handleRecvEvent(int fd, Json::Value* root, std::string str)
{
    if ((*root)["action"].asInt() == 1)
    {
        ByteStreamHandler::writeBytes("./build_file/" + std::to_string((*root)["uid"].asInt()), str);
    }
    if ((*root)["action"].asInt() == 2)
    {
        std::unique_ptr<std::vector<char>> vec_ptr = ByteStreamHandler::readBytes(
            "./build_file/" + std::to_string((*root)["uid"].asInt()));


        // 使用 vector 的数据和大小来创建一个 string
        std::cout << "vec_ptr->size()"<< vec_ptr->size();
        std::string str(vec_ptr->data(), vec_ptr->size());
        EventController::handleSendEvent(fd, root, str);
    }
}

void EventController::handleRecvEvent(int fd, std::string str)
{
    // 处理读取事件的代码
    // 从字符串解析JSON对象

    std::cout << "handleRecvEvent---------:" << std::endl;
    std::cout << str << std::endl;

    Json::Value root;
    Json::Reader reader;
    //
    bool parsingSuccessful = reader.parse(str, root);
    //
    const std::string name = root["Name"].asString();

    std::cout << "Name: " << name << std::endl;

    root["Name"] = "abc";
    this->handleSendEvent(fd, root);

    //    json parsed_json = json::parse(str);

    // 输出解析后的JSON对象
    //    std::cout << "\nParsed JSON:\n" << parsed_json.dump(4) << std::endl;
}

void EventController::handleSendEvent(int fd, const Json::Value& JsonValue)
{
    // 处理写入事件的代码
    Session* session = get_connection_state(fd);
    IoBuffer* io_buffer = session->getSendBuffer();

    Json::FastWriter fastWriter;
    std::string outputJson = fastWriter.write(JsonValue);

    // Remove trailing newline
    if (!outputJson.empty() && outputJson.back() == '\n')
    {
        outputJson.pop_back();
    }
    // Calculate and print the length of the JSON string
    std::cout << "JSON string: " << outputJson << std::endl;
    std::cout << "Length of the JSON string: " << outputJson.length() << std::endl;


    std::cout << "io_buffer->getBufferLen() 1:" << io_buffer->getBufferLen() << std::endl;
    io_buffer->setInt(1);
    std::cout << "io_buffer->getBufferLen() 2:" << io_buffer->getBufferLen() << std::endl;
    io_buffer->setInt((int)outputJson.length());
    std::cout << "io_buffer->getBufferLen() 3:" << io_buffer->getBufferLen() << std::endl;
    io_buffer->writeBuffer((BYTE*)outputJson.data(), (int)outputJson.length());
    std::cout << "io_buffer->getBufferLen() 4:" << io_buffer->getBufferLen() << std::endl;


    io_buffer->filp();

    size_t buff_size = io_buffer->getBufferLen();


    // int count = write(fd, io_buffer->getReadIndexP(), io_buffer->getBufferLen());

    ssize_t total_sent = 0;
    ssize_t bytes_sent;
    while (total_sent < buff_size)
    {
        // std::cout << "io_buffer->getBufferLen()" << io_buffer->getBufferLen() << std::endl;
        bytes_sent = write(fd, io_buffer->getReadIndexP(), io_buffer->getBufferLen());
        if (bytes_sent == -1)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 缓冲区满，现在不能发送更多数据
                // 可以使用select/poll/epoll等待可写事件
                break;
            }
            else
            {
                // 发生了其他错误
                perror("write");
                break;
            }
        }
        else
        {
            // 发送成功，更新已发送字节数
            io_buffer->position += (int)bytes_sent;
            total_sent += bytes_sent;
        }
    }
    std::cout << "total_sent:" << total_sent << std::endl;
    io_buffer->compact();

    // io_buffer->position += io_buffer->getBufferLen();
    // io_buffer->compact();
}

void EventController::handleSendEvent(int fd, const Json::Value* JsonValue, std::string str)
{
    // 处理写入事件的代码
    Session* session = get_connection_state(fd);
    IoBuffer* io_buffer = session->getSendBuffer();

    // Json::FastWriter fastWriter;
    // std::string outputJson = fastWriter.write(JsonValue);

    // Remove trailing newline
    // if (!outputJson.empty() && outputJson.back() == '\n') {
    //     outputJson.pop_back();
    // }
    // Calculate and print the length of the JSON string
    // std::cout << "JSON string: " << outputJson << std::endl;
    // std::cout << "Length of the JSON string: " << outputJson.length() << std::endl;



    std::cout<<"io_buffer->getBufferLen() 1:"<<io_buffer->getBufferLen()<<std::endl;
    if ((*JsonValue)["action"].asInt() == 2)
    {
        io_buffer->setInt(2); //action
        io_buffer->setInt((*JsonValue)["action"].asInt()); //action
        io_buffer->setInt((*JsonValue)["seq"].asInt()); //seq
        io_buffer->setInt((*JsonValue)["uid"].asInt()); //uid
        std::cout<<"io_buffer->getBufferLen() 2:"<<io_buffer->getBufferLen()<<std::endl;
        int packLen= (int)str.length()*2;
        io_buffer->setInt(packLen); //packLen
        // io_buffer->setInt((int)outputJson.length());
        std::cout<<"io_buffer->packLen() 3:"<<packLen<<std::endl;

        const BYTE* bytePtr = reinterpret_cast<const BYTE*>(str.data());
        std::cout << bytePtr<<std::endl;;
        std::cout<<"BYTE*"<<packLen<<std::endl;

        io_buffer->writeBuffer((BYTE*)str.data(), packLen/2);
        std::cout<<"io_buffer->getBufferLen() 4:"<<io_buffer->getBufferLen()<<std::endl;


        std::cout << "(*JsonValue)[action]" << (*JsonValue)["action"].asInt() << std::endl;
        std::cout << "(*JsonValue)[seq]" << (*JsonValue)["seq"].asInt() << std::endl;
        std::cout << "(*JsonValue)[uid] " << (*JsonValue)["uid"].asInt() << std::endl;
        std::cout << "(int)str.length()" << (int)str.length() << std::endl;

        io_buffer->filp();

    }
        std::cout<<"io_buffer->getBufferLen() 5:"<<io_buffer->getBufferLen()<<std::endl;


    CheckSendIoBuffer(fd);




    // io_buffer->position += io_buffer->getBufferLen();
    // io_buffer->compact();
}

int EventController::CheckSendIoBuffer(int fd)
{

    Session* session = get_connection_state(fd);
    IoBuffer* io_buffer = session->getSendBuffer();

    std::cout << "CheckSendIoBuffer" << io_buffer->getBufferLen()<<std::endl;
    if (io_buffer->getBufferLen() == 0)
    {
        return 0;
    }


    size_t buff_size = io_buffer->getBufferLen();


    // int count = write(fd, io_buffer->getReadIndexP(), io_buffer->getBufferLen());

    ssize_t total_sent = 0;
    ssize_t bytes_sent;
    while (total_sent < buff_size)
    {
        // std::cout << "io_buffer->getBufferLen()" << io_buffer->getBufferLen() << std::endl;
        bytes_sent = write(fd, io_buffer->getReadIndexP(), io_buffer->getBufferLen());
        if (bytes_sent == -1)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 缓冲区满，现在不能发送更多数据
                // 可以使用select/poll/epoll等待可写事件


                /*perror("write POOL FULL");
                // ev.events = EPOLLOUT | EPOLLET; // 监听可写事件，not使用边缘触发
                ev.events = EPOLLIN | EPOLLOUT | EPO
                LLET; // 同时监听可读和可写事件，使用边缘触发
                ev.data.fd = session->fd;
                if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, session->fd, &ev) == -1) {
                    perror("epoll_ctl: mod exit(EXIT_FAILURE);");
                    // exit(EXIT_FAILURE);
                }
                break;*/
            }
            else
            {
                // 发生了其他错误
                perror("write");
                break;
            }
        }
        else
        {
            // 发送成功，更新已发送字节数
            io_buffer->position += (int)bytes_sent;
            total_sent += bytes_sent;
        }
    }
    std::cout << "total_sent:" << total_sent << std::endl;
    io_buffer->compact();
    return  io_buffer->getBufferLen();
}

void EventController::handleSendEvent(int fd)
{
    // 处理写入事件的代码
}

void EventController::handleErrorEvent(int fd)
{
    // 处理错误事件的代码
    std::stringstream ss;
    ss << "Error on fd = " << fd;
    LOG_ERROR(ss.str());
    handleCloseConnection(fd);
}

void EventController::handleErrorEvent(int fd, std::string str)
{
    // 处理错误事件的代码
    std::stringstream ss;
    ss << "Error on fd = " << fd;
    LOG_ERROR(ss.str());
    handleCloseConnection(fd);
}

//void EventController::addConnection(int fd) {
//    // 添加新连接的代码
//    connection_buffers[fd] = new IoBuffer();
//}
//
//void EventController::removeConnection(int fd) {
//    // 移除连接的代码
//    delete connection_buffers[fd];
//    connection_buffers.erase(fd);
//}
